<template>
  <div class="details">
    <!-- 导航 -->
    <div class="top">
      <van-nav-bar
        title="商品详情"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
      />
    </div>
    <!-- 产品图 -->
    <div class="imgbox">
      <img :src="coffeeData.large_img" class="auto-img" />
    </div>
    <!-- 产品信息 -->
    <div class="infobox">
      <div class="info">
        <!-- 产品信息头 -->
        <div class="info-top">
          <div class="info-name">{{ coffeeData.name }}</div>
          <div class="info-enname">{{ coffeeData.enname }}</div>
          <div class="info-price">￥{{ coffeeData.price }}</div>
          <van-icon
            :name="likeStatus ? 'star' : 'star-o'"
            class="collect"
            @click="changelike"
            color="#F5A623"
          />
        </div>
        <!-- 产品信息内容 -->
        <div class="info-details">
          <div class="info-title">商品详情</div>
          <div class="info-content">
            <div class="info-describe">
              <div class="left">商品描述</div>
              <div class="text">
                {{ coffeeData.descObj && coffeeData.descObj.describe }}
              </div>
            </div>

            <div class="info-materials">
              <div class="left">主要原料</div>
              <div class="text">
                {{ coffeeData.descObj && coffeeData.descObj.materials }}
              </div>
            </div>
            <div class="info-specification">
              <div class="left">规格选择</div>
              <div class="text">
                {{ coffeeData.descObj && coffeeData.descObj.specificaInfo }}
              </div>
            </div>
            <div class="info-explain">
              <div class="left">描述说明</div>
              <div class="text">
                {{ coffeeData.descObj && coffeeData.descObj.explain }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 商品导航 -->
      <van-goods-action>
        <van-goods-action-icon :icon="caidan" text="菜单" @click="goMenu" />
        <van-goods-action-icon
          :icon="shopBag > 0 ? ingouwudai : gouwudai"
          text="购物袋"
          :badge="shopBag > 0 ? shopBag : ''"
          @click="goBag"
        />
        <van-goods-action-button
          color="#B29293"
          type="warning"
          text="加入购物车"
          @click="addBag"
        />
        <van-goods-action-button
          color="#5D1B1E"
          type="danger"
          text="立即购买"
          @click="pay"
        />
      </van-goods-action>
    </div>
    <!-- 加入购物车 -->
    <van-popup v-model="isOpenShow" position="bottom" closeable>
      <div class="shop-box">
        <div class="shop-top">
          <div class="shop-img">
            <img :src="coffeeData.small_img" class="auto-img" />
          </div>
          <div class="shop-info">
            <div class="shop-name">{{ coffeeData.name }}</div>
            <div class="shop-selected">
              <span>已选：</span>
              <span>{{ rule }}</span>
            </div>
            <div class="shop-price">￥{{ coffeeData.price }}</div>
          </div>
        </div>
        <div class="number-box">
          <div class="num-text">数量</div>
          <div class="num-btn">
            <van-stepper
              v-model="number"
              theme="round"
              button-size="22"
              disable-input
            />
          </div>
        </div>

        <div class="select-box">
          <div
            class="select"
            v-for="(v1, i1) in coffeeData.specificaData"
            :key="i1"
          >
            <div class="select-title">{{ v1.title }}</div>
            <div class="select-item">
              <div
                class="item"
                :class="{ active: v1.activeIndex === i2 }"
                v-for="(v2, i2) in v1.specifica"
                :key="i2"
                @click="selecting(v1, i2)"
              >
                {{ v2.title }}
              </div>
            </div>
          </div>
        </div>
        <div class="btn" v-show="isbBtn">
          <van-button
            type="primary"
            block
            color="#7F2F21"
            round
            @click="addShopBag"
            >加入购物车</van-button
          >
        </div>
        <div class="btn" v-show="!isbBtn">
          <van-button
            type="primary"
            block
            color="#7F2F21"
            round
            @click="payproduct"
            >立即购买</van-button
          >
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import "../assets/less/details.less";
import { mapState, mapMutations } from "vuex";
export default {
  name: "Details",
  data() {
    return {
      gouwudai: require("../assets/images/gouwudai.png"),
      ingouwudai: require("../assets/images/gouwudai_active.png"),
      caidan: require("../assets/images/caidan_active.png"),

      // 咖啡详情信息
      coffeeData: {},

      // 咖啡pid
      coffeePid: "",

      // 显示购物模块
      isOpenShow: false,

      // 订单数
      number: 0,

      // 收藏状态
      likeStatus: false,

      // 选择的规格
      rule: "",

      // 选择显示按钮模块
      isbBtn: true,

      // 定义立即购买sid
      // sid: 0,
    };
  },
  created() {
    //获取咖啡数据
    this.coffeePid = this.$route.params.pid;
    // 获取咖啡数据
    this.getCoffeeData();
    // 查询收藏
    this.coffeeLike();
    // 查询购物袋
    this.inquireBag();
  },
  computed: {
    ...mapState(["shopBag", "isShopBag"]),
  },
  methods: {
    ...mapMutations(["changeShopBag", "changeIsShopBag"]),
    // 返回
    onClickLeft() {
      this.$router.back(); // 等价于this.$router.go(-1)
    },

    // 显示加入购物车
    addBag() {
      this.isOpenShow = true;
      this.isbBtn = true;
    },

    // 显示立即购买
    pay() {
      this.isOpenShow = true;
      this.isbBtn = false;
    },

    // 选择规格
    selecting(item, index) {
      if (item.activeIndex == index) {
        return;
      }
      item.activeIndex = index;

      this.inquireRule();
    },

    // 查询规格
    inquireRule() {
      let ruleArr = [];
      this.coffeeData.specificaData.forEach((v) => {
        ruleArr.push(v.specifica[v.activeIndex].title);
      });
      this.rule = ruleArr.join(" / ");
    },

    // 是否收藏
    changelike() {
      if (this.likeStatus) {
        // 取消收藏
        this.nolike();
      } else {
        // 收藏
        this.like();
      }
    },

    // 收藏
    like() {
      let tokenString = this.$cookies.get("tokenString");

      //当用户未登录的时候跳转到登录页面
      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "post",
        url: this.baseUrl + "/like",
        data: {
          appkey: this.appkey,
          pid: this.coffeePid,
          tokenString: tokenString,
        },
      })
        .then((result) => {
          // console.log(result);
          this.$toast.clear();
          if (result.data.code === 700) {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          } else if (result.data.code === 800) {
            this.likeStatus = true;
          } else {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log(err);
        });
    },

    // 取消收藏
    nolike() {
      let tokenString = this.$cookies.get("tokenString");

      //当用户未登录的时候跳转到登录页面
      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "post",
        url: this.baseUrl + "/notlike",
        data: {
          appkey: this.appkey,
          pid: this.coffeePid,
          tokenString: tokenString,
        },
      })
        .then((result) => {
          // console.log(result);
          this.$toast.clear();
          if (result.data.code === 700) {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          }
          if (result.data.code === 900) {
            if (result.data.result === 1) {
              this.likeStatus = false;
            }
          } else {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log(err);
        });
    },

    // 查询是否收藏
    coffeeLike() {
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "get",
        url: this.baseUrl + "/findlike",
        params: {
          appkey: this.appkey,
          pid: this.coffeePid,
          tokenString: tokenString,
        },
      })
        .then((result) => {
          // console.log(result);
          this.$toast.clear();
          if (result.data.code == 700) {
            return this.$router.push({ name: "Login" });
          }
          if (result.data.code === 1000) {
            if (result.data.result.length > 0) {
              this.likeStatus = true;
            }
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log(err);
        });
    },

    // 获取咖啡详情信息
    getCoffeeData() {
      // console.log(this.coffeePid);
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "get",
        url: this.baseUrl + "/productDetail",
        params: {
          appkey: this.appkey,
          pid: this.coffeePid,
        },
      })
        .then((result) => {
          // console.log(result);
          this.$toast.clear();
          if (result.data.code === 600) {
            let info = result.data.result[0];

            //处理规格选择数据
            let specifica = ["cream", "milk", "sugar", "tem"];

            //保存处理过后的规格选择数据
            info.specificaData = [];

            //保存处理过后的详情信息数据
            info.descObj = {};

            //存储详情中规格的数据
            let specificaInfo = "";

            specifica.forEach((item) => {
              if (!info[item]) {
                return;
              }
              specificaInfo += info[item] + "  ";

              let specificaText = info[item].split("/");

              let specificaObj = {
                title: info[item + "_desc"],
                activeIndex: 0,
                specifica: [],
              };

              specificaText.forEach((v) => {
                let ob = {
                  title: v,
                };
                specificaObj.specifica.push(ob);
              });
              info.specificaData.push(specificaObj);
              // console.log(specificaObj);
            });

            // 处理商品描述信息
            let descArr = info.desc.split("\n");
            // console.log(descArr);
            info.descObj = {
              describe: descArr[0],
              materials: descArr[1].split("：")[1],
              explain: descArr[2],
              specificaInfo: specificaInfo.slice(0, -2),
            };
            this.coffeeData = info;
            // console.log(info);
            // console.log(this.coffeeData);
            // 查询规格
            this.inquireRule();
          } else {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log(err);
        });
    },

    // 添加购物袋
    addShopBag() {
      let tokenString = this.$cookies.get("tokenString");

      //当用户未登录的时候跳转到登录页面
      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "post",
        url: this.baseUrl + "/addShopcart",
        data: {
          appkey: this.appkey,
          pid: this.coffeePid,
          tokenString: tokenString,
          count: this.number,
          rule: this.rule,
        },
      })
        .then((result) => {
          console.log(result);
          this.$toast.clear();
          if (result.data.code === 700) {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          }

          if (result.data.code === 3000) {
            //隐藏购物模块
            this.isOpenShow = false;
            if (result.data.status === 1) {
              // 提交数据到全局属性shopBag
              this.changeShopBag(this.shopBag + 1);
            }

            this.sid = result.data.sid;
          } else {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log(err);
        });
    },

    //立即购买
    payproduct() {
      let tokenString = this.$cookies.get("tokenString");

      //当用户未登录的时候跳转到登录页面
      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "post",
        url: this.baseUrl + "/addShopcart",
        data: {
          appkey: this.appkey,
          pid: this.coffeePid,
          tokenString: tokenString,
          count: this.number,
          rule: this.rule,
        },
      })
        .then((result) => {
          let sid = "";
          console.log(result);
          this.$toast.clear();
          if (result.data.code === 700) {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          }

          if (result.data.code === 3000) {
            //隐藏购物模块
            this.isOpenShow = false;
            if (result.data.status === 1) {
              // 提交数据到全局属性shopBag
              this.changeShopBag(this.shopBag + 1);
            }

            sid = result.data.sid;
            return sid;
          } else {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .then((sid) => {
          console.log(sid);
          this.$router.push({
            name: "Order",
            query: { sids: sid },
          });
        })
        .catch((err) => {
          this.$toast.clear();
          console.log(err);
        });
    },

    // 查询购物袋订单
    inquireBag() {
      if (this.isShopBag) {
        console.log("Details 已经加载过了 ");
        return;
      }

      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "get",
        url: this.baseUrl + "/shopcartRows",
        params: {
          appkey: this.appkey,
          tokenString: tokenString,
        },
      })
        .then((result) => {
          console.log(result);
          this.$toast.clear();
          if (result.data.code == 700) {
            return this.$router.push({ name: "Login" });
          }
          if (result.data.code === 8000) {
            this.changeShopBag(result.data.result);
            this.changeIsShopBag(true);
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log(err);
        });
    },

    // 跳转到菜单页面
    goMenu() {
      this.$router.push({ name: "Menu" });
    },
    // 跳转到购物袋
    goBag() {
      this.$router.push({ name: "Bag" });
    },
  },
};
</script>
